package com.shanwen.shopping.activity;

import android.app.Activity;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.classic.core.log.Logger;
import com.classic.core.utils.DataUtil;
import com.classic.core.utils.DateUtil;
import com.classic.okhttp.base.OkHttpUtils;
import com.shanwen.shopping.R;
import com.shanwen.shopping.consts.Consts;
import com.shanwen.shopping.entity.ModuleContentInfo;
import com.shanwen.shopping.entity.ModuleInfo;
import com.shanwen.shopping.http.ActionHelp;
import com.shanwen.shopping.http.BaseCallback;
import com.shanwen.shopping.utils.PicassoUtil;
import com.shanwen.shopping.view.SuperSwipeRefreshLayout;
import com.shanwen.shopping.utils.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 企业专区列表界面
 */
public class EnterpriseListActivity extends AppBaseActivity implements AdapterView.OnItemClickListener {
    public static final String MODULE_INFO = "moduleInfo";
    @BindView(R.id.ssl_refresh)
    SuperSwipeRefreshLayout sslRefresh;
    @BindView(R.id.enter_content_lv)
    ListView listView;
    @BindView(R.id.tv_no_data)
    TextView tvNoData;

    public long currentPublishTime;
    private int totalNum;//加载的数据
    public ModuleInfo moduleInfo;
    private List<ModuleContentInfo> moduleContentInfoList = new ArrayList<>();

    @Override
    public int getLayoutResId() {
        return R.layout.activity_enterprise_list;
    }

    @Override
    public void initData() {
        super.initData();
        moduleInfo = (ModuleInfo) getIntent().getSerializableExtra(MODULE_INFO);
    }

    @Override
    public void initView() {
        super.initView();
        setTitle(moduleInfo.getModuleName());
        setBackEnabled(true);
        currentPublishTime = 0;
        getData(moduleInfo.getModuleId(), currentPublishTime);
        adapter = new ContentAdapter(this, moduleContentInfoList);
        listView.setAdapter(adapter);

        sslRefresh.setHeaderView(createHeaderView());
        sslRefresh.setFooterView(createFooterView());
        setListener();
    }

    private void setListener() {
        listView.setOnItemClickListener(this);

        sslRefresh.setOnPushLoadMoreListener(new SuperSwipeRefreshLayout.OnPushLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if (totalNum == Consts.PAGE_SIZE) {
                    footerTextView.setText("正在加载...");
                    footerImageView.setVisibility(View.GONE);
                    footerProgressBar.setVisibility(View.VISIBLE);
                    getData(moduleInfo.getModuleId(), currentPublishTime);
                } else {
                    footerTextView.setText("没有更多数据");
                    footerImageView.setVisibility(View.GONE);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            footerImageView.setVisibility(View.VISIBLE);
                            sslRefresh.setLoadMore(false);
                        }
                    }, 500);
                }
            }

            @Override
            public void onPushDistance(int distance) {

            }

            @Override
            public void onPushEnable(boolean enable) {
                footerTextView.setText(enable ? "松开加载" : "上拉加载");
                footerImageView.setVisibility(View.VISIBLE);
                footerImageView.setRotation(enable ? 0 : 180);
            }
        });
        sslRefresh.setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {
            @Override
            public void onRefresh() {
                textView.setText("正在刷新");
                imageView.setVisibility(View.GONE);
                progressBar.setVisibility(View.VISIBLE);
                currentPublishTime = 0;
                getData(moduleInfo.getModuleId(), currentPublishTime);
            }

            @Override
            public void onPullDistance(int distance) {

            }

            @Override
            public void onPullEnable(boolean enable) {
                textView.setText(enable ? "松开刷新" : "下拉刷新");
                imageView.setVisibility(View.VISIBLE);
                imageView.setRotation(enable ? 180 : 0);
            }
        });
    }

    public void getData(long moduleId, final long time) {
        ActionHelp.qryModuleContentList(activity, "3", moduleId, time, Consts.PAGE_SIZE,
                new BaseCallback() {
                    @Override
                    public void parse(String data) {
                        hide();
                        try {
                            final JSONArray array = new JSONObject(data).getJSONArray("modelContentList");
                            List<ModuleContentInfo> response = new ArrayList<>();
                            if (null != array) {
                                for (int i = 0; i < array.length(); i++) {
                                    JSONObject currentObj = array.getJSONObject(i);
                                    ModuleContentInfo.Detail detail = JSON.parseObject(currentObj.getString("dataJson"), ModuleContentInfo.Detail.class);

                                    response.add(new ModuleContentInfo(detail,
                                            currentObj.getString("type"),
                                            currentObj.getLong("moduleContentId"),
                                            currentObj.getLong("publishTime")
                                    ));
                                }
                            }
                            if (time == 0) {
                                moduleContentInfoList.clear();
                                if (!DataUtil.isEmpty(response)) {
                                    moduleContentInfoList.addAll(response);
                                    currentPublishTime = moduleContentInfoList.get(moduleContentInfoList.size() - 1).getPublishTime();
                                } else {
                                    tvNoData.setVisibility(View.VISIBLE);
                                }
                            } else {
                                moduleContentInfoList.addAll(response);
                                currentPublishTime = moduleContentInfoList.get(moduleContentInfoList.size() - 1).getPublishTime();
                            }
                            totalNum = moduleContentInfoList.size();
                            if (totalNum == 0) {
                                tvNoData.setVisibility(View.VISIBLE);
                            } else {
                                tvNoData.setVisibility(View.GONE);
                                adapter.setData(moduleContentInfoList);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(int code, String errorMessage) {
                        super.onError(code, errorMessage);
                        Logger.e(errorMessage);
                        hide();
                    }
                }
        );
    }

    private void hide() {
        footerImageView.setVisibility(View.VISIBLE);
        footerProgressBar.setVisibility(View.GONE);
        progressBar.setVisibility(View.GONE);
        sslRefresh.setLoadMore(false);
        sslRefresh.setRefreshing(false);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ModuleContentInfo.Detail detail = moduleContentInfoList.get(position).getDataJson();
        if (null == detail) {
            return;
        }
        if (DataUtil.isEmpty(detail.getHtmlUrl())) {
            Utils.showToast(activity, "详情页面url为空");
            return;
        }
        WebViewActivity.start(activity, DataUtil.isEmpty(detail.getTitle()) ? "" : detail.getTitle(), detail.getHtmlUrl());
    }

    private ContentAdapter adapter;

    private class ContentAdapter extends BaseAdapter {
        List<ModuleContentInfo> data;
        Activity activity;

        public void setData(List<ModuleContentInfo> data) {
            this.data = data;
            notifyDataSetChanged();
        }

        private ContentAdapter(Activity activity, List<ModuleContentInfo> data) {
            this.activity = activity;
            this.data = data;
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            ViewHolder holder;
            if (view == null) {
                holder = new ViewHolder();
                view = LayoutInflater.from(activity).inflate(R.layout.fragment_main_item, null);
                holder.main_item_cover = (ImageView) view.findViewById(R.id.main_item_cover);
                holder.main_item_title = (TextView) view.findViewById(R.id.main_item_title);
                holder.main_item_intro = (TextView) view.findViewById(R.id.main_item_intro);
                holder.main_item_date = (TextView) view.findViewById(R.id.main_item_date);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            ModuleContentInfo moduleContentInfo = data.get(position);
            PicassoUtil.load(activity, moduleContentInfo.getDataJson().getCoverImageUrl(), holder.main_item_cover);
            holder.main_item_date.setText(DateUtil.formatDate(DateUtil.FORMAT_DATE, moduleContentInfo.getPublishTime()));
            holder.main_item_intro.setText(moduleContentInfo.getDataJson().getShortDesc());
            holder.main_item_title.setText(moduleContentInfo.getDataJson().getTitle());
            return view;
        }

        class ViewHolder {
            ImageView main_item_cover;
            TextView main_item_title;
            TextView main_item_intro;
            TextView main_item_date;
        }
    }

    // Header View
    private ProgressBar progressBar;
    private TextView textView;
    private ImageView imageView;
    // Footer View
    private ProgressBar footerProgressBar;
    private TextView footerTextView;
    private ImageView footerImageView;

    private View createHeaderView() {//设置头布局
        View headerView = LayoutInflater.from(sslRefresh.getContext()).inflate(R.layout.layout_head, null);
        progressBar = (ProgressBar) headerView.findViewById(R.id.pb_view);
        textView = (TextView) headerView.findViewById(R.id.text_view);
        textView.setText("下拉刷新");
        imageView = (ImageView) headerView.findViewById(R.id.image_view);
        imageView.setVisibility(View.VISIBLE);
        imageView.setImageResource(R.mipmap.xrefreshview_arrow);
        progressBar.setVisibility(View.GONE);
        return headerView;
    }

    private View createFooterView() {//设置脚布局
        View footerView = LayoutInflater.from(sslRefresh.getContext()).inflate(R.layout.layout_footer, null);
        footerProgressBar = (ProgressBar) footerView.findViewById(R.id.footer_pb_view);
        footerImageView = (ImageView) footerView.findViewById(R.id.footer_image_view);
        footerTextView = (TextView) footerView.findViewById(R.id.footer_text_view);
        footerProgressBar.setVisibility(View.GONE);
        footerImageView.setVisibility(View.VISIBLE);
        footerImageView.setImageResource(R.mipmap.xrefreshview_arrow);
        footerTextView.setText("上拉加载更多...");
        return footerView;
    }

    @Override
    protected void onDestroy() {
        OkHttpUtils.cancelTag(this);
        super.onDestroy();
    }
}
